/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.apt.tag;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Lambach
 */
public class Connect_DB {

    public static Connection getConnection() {
        Connection cnn = null;
        Properties p = new Properties();
        try {
            p.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("config.properties"));
//            p.load(new FileInputStream("src/config.properties"));
//            p.load(getServletContext().getResourceAsStream("/WEB-INF/config.properties"));
            String databaseName = p.getProperty("databaseName");
            String userName = p.getProperty("userName");
            String password = p.getProperty("passWord");
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");//LAMBACH-PC
            cnn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=" + databaseName + "", userName, password);
        } catch (ClassNotFoundException ce) {
            System.out.println(ce);
        } catch (SQLException ce) {
            System.out.println(ce);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Connect_DB.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Connect_DB.class.getName()).log(Level.SEVERE, null, ex);
        }
        return cnn;
    }

    public static void close(ResultSet rs, Statement st, PreparedStatement ps, Connection cn) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException ex) {
                Logger.getLogger(Connect_DB.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        if (ps != null) {
            try {
                ps.close();
            } catch (SQLException ex) {
                Logger.getLogger(Connect_DB.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        if (st != null) {
            try {
                st.close();
            } catch (SQLException ex) {
                Logger.getLogger(Connect_DB.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        if (cn != null) {
            try {
                cn.close();
            } catch (SQLException ex) {
                Logger.getLogger(Connect_DB.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}
